package com.guli.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.guli.common.to.mq.OrderTo;
import com.guli.common.to.mq.StockDetailTo;
import com.guli.common.to.mq.StockLockedTo;
import com.guli.common.utils.R;
import com.guli.gulimall.ware.dao.WareSkuDao;
import com.guli.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.guli.gulimall.ware.entity.WareOrderTaskEntity;
import com.guli.gulimall.ware.feign.OrderFeignService;
import com.guli.gulimall.ware.feign.ProductFeignService;
import com.guli.gulimall.ware.service.WareOrderTaskDetailService;
import com.guli.gulimall.ware.service.WareOrderTaskService;
import com.guli.gulimall.ware.service.WareSkuService;
import com.guli.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    /**
     * 库存自动解锁 ，消息队列监听
     * 1.下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。之前锁定的库存就要自动解锁
     * 2.订单失败
     *
     * @param to
     * @param message
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        log.info("收到解锁库存的消息");
        try {
            //当前消息是否是被第二次及以后（重新）派发过来了。
//            Boolean redelivered = message.getMessageProperties().getRedelivered();
            wareSkuService.unLockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //消息拒绝以后，重新放到队列,让别人继续消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
        log.info("库存解锁完成。");
    }

    /**
     * 订单关闭之后解锁库存
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo order, Message message, Channel channel) throws IOException {
        log.info("订单关闭准备解锁库存。。");
        try {
            wareSkuService.unLockStock(order);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //消息拒绝以后，重新放到队列,让别人继续消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
